/**
 * Created by Json on 2015/1/4.
 */
(function () {
	!(/AppleWebKit/).test( navigator.userAgent ) && document.body.classList.add( "not-webkit" );
	var onTap = fp.onTap,
		loop = fp.loop,
		loopArray = fp.loopArray,
		loopObj = fp.loopObj,
		CSS = fp.CSS,
		element = fp.element;

	window.color = {"background" : "#FFFFFF"};

	var MB = 1024 * 1024;
	var KB = 1024;
	var querySelector = document.querySelector.bind( document );
	var systemTemPlate = makeTemplate();
	var addPageBtn = querySelector( ".edit-page-add-page-btn" );
	var addPageSettingPage = querySelector( ".edit-page-add-page-setting-page" );
	addPageSettingPage.isLoadTemplate = false;
	var editPageRight = querySelector( ".edit-page-right" );
	var editPageLeft = querySelector( ".edit-page-left" );
	var previewPage = querySelector( ".preview-page" );

	var notSurppotList = {
		21 : true, // 外链接
		39 : true, // 多图
		40 : true, // 联系页
		41 : true, // 地图页
		42 : true, // 视频页
		43 : true, // 报名页
		44 : true, // 涂抹
		52 : true, // 情书
		31 : true, // 文图010
		32 : true, // 文图010
		60 : true,
		63 : true  // 文字多图
	};

	function staticImgSrc( src ) {
		return ((contentPath || virtualPath) + "/Content/" + src).toLowerCase();
	}

	function makeTemplate() {
		var template = querySelector( "#template" );
		document.body.removeChild( template );
		var make = function ( selector ) {
			try {
				var node = template.querySelector( selector );

			}
			catch ( e ) {
				console.log( e );
			}
			var newNode = node.cloneNode( true );
			return newNode;
		};
		return {
			make : make
		}
	}

	function openInnerPage( page ) {
		page.classList.remove( "hide" );
	}

	function closeInnerPage( page ) {
		page.classList.add( "hide" );
	}

	function openSlidePage( page ) {
		var border = querySelector( ".edit-page-slide-page-border" );
		if ( border.querySelector( ".slide-out.slide-page" ) ) {
			// 如果当前已经有一个页面是滑出状态，则关闭该页面
			border.querySelector( ".slide-out.slide-page" ).classList.remove( "slide-out" );
		}
		page.classList.add( "slide-out" );
		border.classList.add( "slide-out" );
		querySelector( ".edit-page-pre-page-btn" ).classList.add( "hide" );
		querySelector( ".edit-page-next-page-btn" ).classList.add( "hide" );
		querySelector( ".edit-page-add-page-btn" ).classList.add( "hide" );
		querySelector( ".edit-page-add-page-setting-page" ).classList.add( "hide" );
	}

	function closeSlidePage( page ) {
		page.classList.remove( "slide-out" );
		querySelector( ".edit-page-slide-page-border" ).classList.remove( "slide-out" );
		if ( !querySelector( ".edit-page-slide-page-border .slide-out" ) ) {
			querySelector( ".edit-page-pre-page-btn" ).classList.remove( "hide" );
			querySelector( ".edit-page-next-page-btn" ).classList.remove( "hide" );
			querySelector( ".edit-page-add-page-btn" ).classList.remove( "hide" );
		}
	}

	function closeAllSlidePage() {
		// 如果当前编辑图片或编辑文字页面是打开状态，则切换页面时候要关闭这两个页面（当然，以后可能会更多的页面，比如编辑地图页面等）
		querySelector( ".edit-page-slide-page-border " ).classList.contains( "slide-out" ) && querySelector( ".edit-page-slide-page-border " ).classList.remove( "slide-out" );
		querySelector( ".slide-page.slide-out" ) && querySelector( ".slide-page.slide-out" ).classList.remove( "slide-out" );
		querySelector( ".edit-page-pre-page-btn" ).classList.remove( "hide" );
		querySelector( ".edit-page-next-page-btn" ).classList.remove( "hide" );
	}

	// 添加新頁面
	function presetAddPage() {
		addPageSettingPage.addEventListener( "mouseover", function () {
			addPageSettingPage.classList.add( "top" );
		}, false );
		addPageSettingPage.addEventListener( "mouseout", function () {
			addPageSettingPage.classList.remove( "top" );
		}, false );
		// 关闭页面
		onTap( addPageSettingPage.querySelector( ".close-add-page-setting-page-btn" ), function () {
			closeInnerPage( addPageSettingPage );
		} );
		addPageSettingPage.querySelector( ".close-add-page-setting-page-btn2" ).onclick = function () {
			closeInnerPage( addPageSettingPage );
		};
		var makeSureBtn = querySelector( ".edit-page-add-page-setting-page .edit-add-page-btn" );
		onTap( makeSureBtn, function () {
			// 确认添加新的页面
			fp.message( {
				text : "正在添加新页面"
			} );
			fpInvokeAPI.addPage( makeSureBtn.templateID, function ( data ) {
				// todo 添加新的页面回调
				if ( data.code == 200 ) {
					// 添加成功
					fp.message( {
						text : "添加成功"
					} );
					var li = appendOnePage( data.data, document.querySelectorAll( ".thumbnail-page-list li.show" ).length + 1, function ( page ) {
						// 将最新添加的页面映射到主屏幕
						mappingToScreen( page );
					} );
					//　要自动滑到最后,将最新页面选中
					var pageListBorder = querySelector( ".edit-page-left ul" );
					pageListBorder.scrollTop = pageListBorder.querySelectorAll( "li.show" ).length * 154 - pageListBorder.offsetHeight;
					pageListBorder.querySelector( "li.select" ).classList.remove( "select" );
					li.classList.add( "select" );
				}
			} );
			//closeInnerPage( addPageSettingPage );
		} );
	}

	// 編輯圖片 包括页面的弹出、关闭以及一切与此有关的操作
	function slidePageEditBgImg() {
		var openBtn = querySelector( ".edit-page-edit-bgimg-btn" );
		// 编辑背景图片页面
		var updateImgBtn = querySelector( ".slide-edit-bgimg-updata-btn" );
		var fileInput = querySelector( ".slide-page-edit-bgimg .cropit-image-input" );
		var page = querySelector( ".slide-page-edit-bgimg" );
		var saveBtn = page.querySelector( ".slide-edit-bgimg-save-btn" );
		page.addEventListener( "mouseover", function () {
			page.classList.add( "top" );
		}, false );
		page.addEventListener( "mouseout", function () {
			page.classList.remove( "top" );
		}, false );
		$( ".slide-page-edit-bgimg .crop-img-border" ).cropit();
		updateImgBtn.onclick = function () {
			fileInput.click();
		};
		querySelector( ".close-slide-page-edit-bgimg" ).onclick = function () {
			closeSlidePage( page );
		};
		openBtn.onclick = function () {
			page.classList.contains( "slide-out" ) ? closeSlidePage( page ) : openSlidePage( page );
		};
		saveBtn.onclick = function () {
			var pageData = page.pageData;
			var mediaData = page.mediaData;
			var mediaAtrr = JSON.parse( mediaData.Attributes );
			var crop = $( '.slide-page-edit-bgimg .crop-img-border' ).cropit( "cropInfo" );
			var inputFile = page.querySelector( ".cropit-image-input" );
			if ( inputFile.files.length == 0 ) {
				fp.message( {
					text : "请选择更换的图片"
				} );
				return;
			}
			if ( inputFile.files[0].size > 4 * MB ) {
				fp.message( {
					text : "图片不能超过4MB"
				} );
				return;
			}
			// 保存對圖片的修改
			var parms = {
				"omid" : mediaData.ID,
				"pid" : pageData.Guid,
				"attr" : mediaData.Attributes,
				Zoom : crop.zoom * mediaAtrr.W / 256,
				OffsetX : Math.abs( crop.offset.x ) * mediaAtrr.W / 256,
				OffsetY : Math.abs( crop.offset.y ) * mediaAtrr.W / 256,
				Width : mediaAtrr.W,
				Height : mediaAtrr.H,
				Shape : mediaAtrr.Shape || 0,
				Scale : 2,
				HasBorder : mediaAtrr.HasBorder,
				BorderWidth : mediaAtrr.BorderWidth,
				BorderColor : mediaAtrr.BorderColor,
				CornerRadius : mediaAtrr.CornerRadius
			};
			var fd = new window.FormData();
			loopObj( parms, function ( key, value ) {
				fd.append( key, value );
			} );
			fd.append( "blob-fileName", inputFile.files[0].name );
			fd.append( "imgFile", inputFile.files[0], inputFile.files[0].name );
			fp.message( {
				text : "正在保存"
			} );
			page.querySelector( ".cropit-image-preview" ).style.backgroundImage = null;
			// 清空input[file]，允许两次上传同一张图片
			page.querySelector( "form.input-file" ).reset();
			closeSlidePage( page );
			var curLi = querySelector( "li.page-list.select" );
			fpInvokeAPI.saveImageConfig( {
				data : fd,
				success : function ( data ) {
					if ( data.code == 200 ) {
						fp.message( {
							text : "保存完毕"
						} );
						// 更新这个页面的数据
						for ( var i = 0; i < curLi.pageData.Medias.length; i++ ) {
							if ( curLi.pageData.Medias[i].ID == data.data.PrimaryId ) {
								//  找到了被修改的组件
								//  由于此处只是修改了图片内容，位置什么的信息并没有修改，所以只需要替换图片组建的url即可
								curLi.pageData.Medias[i].Guid = data.data.Guid;
								curLi.pageData.Medias[i].ID = data.data.PrimaryId;
								curLi.pageData.Medias[i].Uri = data.data.Url;
								// 生成新的页面
								fp.message( {
									text : "正在生成新页面，请稍等"
								} );
								var newPage = makePage( curLi.pageData, function () {
									curLi.removeChild( curLi.querySelector( ".page" ) );
									curLi.appendChild( newPage );
									// 是否映射到主屏幕，这要依据当前选中的li，假如用户已经等不及渲染（渲染比较慢）
									//　这时候用户可能会换看其他的页面，这时候就不能做映射到主屏幕的操作了，所以要判断
									if ( querySelector( "li.page-list.select" ).pageData.Id == curLi.pageData.Id ) {
										mappingToScreen( newPage );
									}
								} );
								break;
							}
						}
					}
				}
			} );
		}
	}

	// 编辑文字
	function slidePageEditWord() {
		var page = querySelector( ".slide-page-edit-word" );
		var text = querySelector( ".slide-page-edit-word .edit-word-text" );
		var wordCount = querySelector( ".slide-page-edit-word .edit-text-word-count" );
		var colorsBorder = querySelector( ".edit-word-color-border" );
		var moreColorBtn = querySelector( ".edit-word-show-more-color-btn" );
		var moreFontFamilyBtn = querySelector( ".edit-word-show-more-font-family-btn" );
		var moreAnimationBtn = querySelector( ".edit-word-show-more-font-animation-btn" );
		var fontFamilyBorder = querySelector( ".edit-font-family-border" );
		var wordAnimationBorder = querySelector( ".edit-page-word-animation" );
		var vernier = querySelector( ".edit-word-font-family-vernier" );
		var animationVernier = querySelector( ".edit-word-font-animation-vernier" );
		var saveBtn = page.querySelector( ".edit-word-save-btn" );
		page.addEventListener( "mouseover", function () {
			page.classList.add( "top" );
		}, false );
		page.addEventListener( "mouseout", function () {
			page.classList.remove( "top" );
		}, false );
		text.addEventListener( "keydown", function () {
			wordCount.innerHTML = this.value.length + "/" + this.maxLength;// 每次弹出这个页面都应该执行一次这行代码
		}, false );
		// 颜色
		var colors = ["#000", "#8b8b8b", "#ffffff", "#c3e5a8", "#88cb55", "#578c2e",
			"#eff6ad", "#deec5f", "#fefbb0", "#fdf666", "#f2e933", "#fbde9d", "#f8c042",
			"#c68c1f", "#fad19c", "#f6a43f", "#f8b79d", "#f46f40", "#cc3c16", "#f6a3a0",
			"#f24a47", "#a211d", "#84143f", "#ee91b3", "#da1c68", "#84143f", "#d87bfb",
			"#651a8c", "#ac34eb", "#651a8c", "#a077fa", "#4a2ee2", "#2a1680", "#99b8fc",
			"#3373f9", "#1f43c9", "#89defb", "#48bbf9", "#2c7aa2"];
		// 生成颜色
		loop( colors.length, function ( i ) {
			var colorBox = element( "div", {classList : "edit-color-box"}, colorsBorder );
			var colorItem = element( "div", {classList : "edit-color-item"}, colorBox );
			CSS( colorItem, {
				"background-color" : colors[i]
			} );
			colorBox.fpFontColor = colors[i];
			i == 0 && colorBox.classList.add( "select" );
			colorBox.onclick = function () {
				// 先去掉選中的顔色
				page.querySelector( ".edit-color-box.select" ) && page.querySelector( ".edit-color-box.select" ).classList.remove( "select" );
				colorBox.classList.add( "select" );
			};
		} );

		// 这个函数的作用就是根据给的颜色值，遍历一遍颜色选择器，如果遍历到了，就把该颜色选择器选中，这个函数用在初始化上
		// 刚进入这个页面的时候，如果这个作品被编辑过，就应该会有文字的颜色等信息，这时候打开文字编辑页面需要设定一个初始
		// 值，这个函数就是干这个用的，如果给定的颜色为null，或者遍历一遍之后没有发现匹配的，就不选择了。老作品在数据库中
		// 没有字体等数据
		page.selectColor = function ( color ) {
			// color是一個十六进制的数字，带着#符号，每个edit-color-box上面都有一个fpFontColor字段保存自己代表的颜色
			var boxes = page.querySelectorAll( ".edit-color-box" ), found = false;
			if ( color ) {
				for ( var i = 0; i < boxes.length; i++ ) {
					if ( color == boxes[i].fpFontColor ) {
						page.querySelector( ".edit-color-box.select" ) && page.querySelector( ".edit-color-box.select" ).classList.remove( "select" );
						boxes[i].classList.add( "select" );
						found = true;
						break;
					}
				}
			}
			//如果未找到值 则什么也不选中
			if ( !found ) {
				page.querySelector( ".edit-color-box.select" ) && page.querySelector( ".edit-color-box.select" ).classList.remove( "select" );
			}
		};

		page.selectFontFamily = function ( fontFamily ) {
			var items = page.querySelectorAll( ".edit-font-family-item" ), found = false;
			if ( fontFamily ) {
				for ( var i = 0; i < items.length; i++ ) {
					if ( fontFamily == items[i].fpFontFamily ) {
						page.querySelector( ".edit-font-family-item.select" ) && page.querySelector( ".edit-font-family-item.select" ).classList.remove( "select" );
						items[0].classList.add( "select" );
						// 交换第一个字体和当前字体的background，让默认的字体永远当地一位
						CSS( vernier, {
							left : "15px",
							top : "16px"
						} );
						var tempbg = items[i].style.background;
						items[i].style.background = items[0].style.background;
						items[0].style.background = tempbg;
						var tempFontFamily = items[i].fpFontFamily;
						items[i].fpFontFamily = items[0].fpFontFamily;
						items[0].fpFontFamily = tempFontFamily;
						found = true;
						break;
					}
				}
			}
			if ( !found ) {
				page.querySelector( ".edit-font-family-item.select" ) && page.querySelector( ".edit-font-family-item.select" ).classList.remove( "select" );
			}
		};

		page.selectFontAnimation = function ( fontAnimation ) {
			var items = page.querySelectorAll( ".edit-word-word-animation" ), found = false;
			if ( fontAnimation ) {
				for ( var i = 0; i < items.length; i++ ) {
					if ( fontAnimation == items[i].fpFontAnimationId ) {
						page.querySelector( ".edit-word-word-animation.select" ) && page.querySelector( ".edit-word-word-animation.select" ).classList.remove( "select" );
						items[0].classList.add( "select" );
						//var x = i % 4;
						//var y = (i / 4) >> 0;
						//CSS( animationVernier, {
						//	left : x * 72 + 15 + "px",
						//	top : y * 58 + 16 + "px"
						//} );
						// 交换第一个字体和当前字体的background，让默认的字体永远当地一位
						CSS( animationVernier, {
							left : "15px",
							top : "16px"
						} );
						var tempbg = items[i].innerHTML;
						items[i].innerHTML = items[0].innerHTML;
						items[0].innerHTML = tempbg;
						var tempFontAnimationId = items[i].fpFontAnimationId;
						items[i].fpFontAnimationId = items[0].fpFontAnimationId;
						items[0].fpFontAnimationId = tempFontAnimationId;
						found = true;
						break;
					}
				}
			}
			if ( !found ) {
				page.querySelector( ".edit-word-word-animation.select" ) && page.querySelector( ".edit-word-word-animation.select" ).classList.remove( "select" );
			}
		};

		page.fillText = function ( textWord ) {
			text.value = "";
			text.value = textWord;
			wordCount.innerHTML = textWord.length > 200 ? "200/200" : textWord.length + "/200";
		};

		moreColorBtn.onclick = function () {
			moreColorBtn.classList.toggle( "show-more" );
			colorsBorder.classList.toggle( "show-more" );
		};
		var fontFamily = ["Champagne & Limousines", "Arial", "Verdana", "Times New Roman",
			"Impact", "Chalkduster", "FZLanTingHeiS-UL-GB", "FZJunHeiS-EL-GB",
			"ZHSRXT-GBK", "FZLanTingKanHei-R-GBK", "Microsoft YaHei Light",
			"FZLanTingHeiS-B-GB", "FZZhengHeiS-M-GB", "FZPinShangHeiS-R-GB",
			"SimSun", "KaiTi", "FZFengYaSongS-GB", "造字工房朗宋（非商用）常规体",
			"汉仪菱心体简", "DFPLiJinHeiW8-GB", "DFPWaWaW5-GB", "FZJingLeiS-R-GB",
			"HanziPen SC", "FZHanJian-R-GB", "叶根友刀锋黑草", "叶根友毛笔行书",
			"书体坊禚效锋行草体", "lixukexingshu"];
		loop( fontFamily.length, function ( i ) {
			var border = element( "div", {classList : "edit-font-family-item"}, fontFamilyBorder );
			border.fpFontFamily = fontFamily[i];
			var fontimg = staticImgSrc( "image/font-family-" + (i + 1) + ".png" );
			CSS( border, {
				"background" : "url(" + fontimg + ") no-repeat",
				"background-size" : "72px auto"
			} );
			i == 0 && border.classList.add( "select" );
			border.index = i;
			border.onclick = function () {
				if ( border.index > 3 && !moreFontFamilyBtn.classList.contains( "show-more" ) ) {
					// 如果这时候没有放下来，而且点击的是被藏起来的，则直接返回（下面漏了一点，有可能点到5、6、7、8号字体）
					return;
				}
				page.querySelector( ".edit-font-family-item.select" ) && page.querySelector( ".edit-font-family-item.select" ).classList.remove( "select" );
				border.classList.add( "select" );
				// 点击中后要滑动游标
				var x = border.index % 4;
				var y = (border.index / 4) >> 0;
				CSS( vernier, {
					left : x * 72 + 15 + "px",
					top : y * 58 + 16 + "px"
				} );
			}
		} );
		moreFontFamilyBtn.onclick = function () {
			moreFontFamilyBtn.classList.toggle( "show-more" );
			fontFamilyBorder.classList.toggle( "show-more" );
		};
		//动画
		var animations = [
			{
				"name" : "默认",
				"id" : null
			},
			{
				"name" : "左飞入",
				"id" : "fly-into-left"
			},
			{
				"name" : "右飞入",
				"id" : "fly-into-right"
			},
			{
				"name" : "上飞入",
				"id" : "fly-into-top"
			},
			{
				"name" : "下飞入",
				"id" : "fly-into-bottom"
			},
			{
				"name" : "左浮现",
				"id" : "emerge-left"
			},
			{
				"name" : "右浮现",
				"id" : "emerge-right"
			},
			{
				"name" : "上浮现",
				"id" : "emerge-top"
			},
			{
				"name" : "下浮现",
				"id" : "emerge-bottom"
			},
			{
				"name" : "从小变大",
				"id" : "scale"
			},
			{
				"name" : "淡入",
				"id" : "fade-in"
			},
			{
				"name" : "回旋",
				"id" : "circle-round"
			},
			{
				"name" : "远近翻转",
				"id" : "round-from-far-and-near"
			},
			{
				"name" : "曲线向上",
				"id" : "curve-up"
			},
			{
				"name" : "缩小",
				"id" : "shrink"
			},
			{
				"name" : "落下抖动",
				"id" : "fall-down-and-shake"
			}
		];
		loop( animations.length, function ( i ) {
			var item = element( "div", {
				classList : "edit-word-word-animation"
			}, wordAnimationBorder );
			item.fpFontAnimationId = animations[i]["id"];
			item.innerHTML = animations[i]["name"];
			i == 0 && item.classList.add( "select" );
			item.onclick = function () {
				page.querySelector( ".edit-word-word-animation.select" ) && page.querySelector( ".edit-word-word-animation.select" ).classList.remove( "select" );
				item.classList.add( "select" );
				// 点击中后要滑动游标
				var x = i % 4;
				var y = (i / 4) >> 0;
				console.log( x, y );
				CSS( animationVernier, {
					left : x * 72 + 15 + "px",
					top : y * 58 + 16 + "px"
				} );
			}
		} );
		moreAnimationBtn.onclick = function () {
			moreAnimationBtn.classList.toggle( "show-more" );
			wordAnimationBorder.classList.toggle( "show-more" );
		};

		//关闭页面
		querySelector( ".close-edit-word-page-btn" ).onclick = function () {
			closeSlidePage( page );
		};

		// 可编辑的属性
		var configList = {
			"Animation" : true,
			"Color" : true,
			"FontFamily" : true
		};
		// 保存文字配置
		saveBtn.onclick = function () {
			var mediaAttr = JSON.parse( page.textInfo.Attributes );

			var sendData = {
				model : {
					"Guid" : page.textInfo.Guid,// 部件的guid
					"Text" : text.value,
					"ID" : page.textInfo.ID,// 部件的id
					"Category" : page.textInfo.Category,
					"ActionLink" : page.textInfo.ActionLink,
					"LayoutId" : page.pageData.LayoutId,
					"Animation" : (function () {
						// 得到选择的动画
						var tar = page.querySelector( ".edit-word-word-animation.select" );
						return tar ? tar.fpFontAnimationId : mediaAttr.Animation;
					})(),
					"Color" : (function () {
						var tar = page.querySelector( ".edit-color-box.select" );
						return tar ? tar.fpFontColor : mediaAttr.Color;
					})(),
					"FontFamily" : (function () {
						var tar = page.querySelector( ".edit-font-family-item.select" );
						return tar ? tar.fpFontFamily : mediaAttr.FontFamily;
					})()
				},
				pid : page.pageData.Guid// page的id
			};

			//model["customenable"];
			if ( sendData.model.Animation != mediaAttr.Animation ) {
				sendData["customenable"] = true;
			}
			loopObj( mediaAttr, function ( key, value ) {
				if ( !sendData.model[key] ) {
					// 如果data.model中没有这项数据，则采用textinfo.Attributes中的
					sendData.model[key] = value;
				}
			} );
			fp.message( {
				text : "正在保存"
			} );
			fpInvokeAPI.saveTextConfig( sendData, function ( data ) {
				if ( data.code == 200 ) {
					// 如果修改成功，需要修改页面，以便最新的页面能够实时显示出来
					fp.message( {
						text : "修改成功，请稍等"
					} );
					var curli = querySelector( "li.page-list.select" );
					for ( var me = 0; me < curli.pageData.Medias.length; me++ ) {
						// 寻找匹配的组件
						if ( data.data.PrimaryId == curli.pageData.Medias[me].ID ) {
							// 找到了，更新页面组件数据
							var attr = JSON.parse( curli.pageData.Medias[me].Attributes );
							attr.Color = sendData.model.Color;
							attr.Animation = sendData.model.Animation;
							attr.FontFamily = sendData.model.FontFamily;
							curli.pageData.Medias[me].Attributes = JSON.stringify( attr );
							curli.pageData.Medias[me].Uri = data.data.Url;
							curli.pageData.Medias[me].Text = data.data.Text;
							curli.pageData.Medias[me].ID = data.data.ID;
							curli.pageData.Medias[me].Guid = data.data.Guid;
							// 生成新的页面
							var newPage = makePage( curli.pageData, function () {
								curli.removeChild( curli.querySelector( ".page" ) );
								curli.appendChild( newPage );
								mappingToScreen( newPage );
							} );
							break;
						}
					}
				}
				else {
					fp.message( {
						text : "修改失败，请重新操作"
					} );
				}
				console.log( data );
			} );
			closeSlidePage( page );
		};
	}

	// 用戶保存设置的时候调用这个函数，音乐和个人配置都要使用.配置音乐的话isMusic为true
	function saveUserConfig( isMusic, callback ) {
		var crop = $( ".edit-setting-page .crop-img-border" ).cropit( "cropInfo" );
		var inputFile = querySelector( ".edit-setting-page .crop-img-border .cropit-image-input" );
		var fd = new FormData();
		if ( !isMusic && inputFile.files.length != 0 ) {
			// 添加头像文件，在这里不会验证文件大小是否超过限制，应该在调用这个函数之前就验证
			fd.append( "blob-fileName", inputFile.files[0].name );
			fd.append( "logo-thumbnail", inputFile.files[0], inputFile.files[0].name );
		}
		loopObj( {
			"Id" : window.workId,
			"Title" : querySelector( ".edit-setting-title textarea" ).value,
			"Description" : querySelector( ".edit-description textarea" ).value,
			"Thumbnail" : querySelector( ".edit-page-theme-thumbnail img" ).src,
			"Switch" : querySelector( ".edit-setting-page .page-turning-animation" ).value,
			"Mode" : querySelector( ".edit-setting-page .page-turning-gesture" ).value,
			"BackgroundMusic" : !isMusic ? querySelector( ".edit-music-make-sure" ).musicUrl : querySelector( ".edit-music-page .select.item .name" ).music.url,
			"Zoom" : crop.zoom,
			"OffsetX" : Math.abs( crop.offset.x ),
			"OffsetY" : Math.abs( crop.offset.y ),
			"Width" : 100,
			"Height" : 100,
			"Scale" : 2,
			"CustomCopyrightEnable" : querySelector( ".edit-setting-page .page-turning-signature" ).value == "custom"
		}, function ( key, value ) {
			fd.append( key, value );
		} );
		fpInvokeAPI.saveConfig( {
			data : fd,
			success : callback
		} );
	}

	// 编辑音乐
	function pageEditMusic() {
		var openBtn = querySelector( ".edit-page-music-setting-btn" );
		var closeBtn = querySelector( ".close-edit-music-page" );
		var page = querySelector( ".edit-music-page" );
		var systemMusicBtn = querySelector( ".edit-music-system-music-list-btn" );
		var userMusicBtn = querySelector( ".edit-music-user-music-list-btn" );
		var systemList = querySelector( ".edit-music-system-music-list" );
		var userList = querySelector( ".edit-music-user-music-list" );
		var inputMusicFile = querySelector( ".edit-music-user-music-list .edit-music-user-file-up" );
		var updateMusicBtn = querySelector( ".edit-music-user-music-list .update-music" );
		var audio = querySelector( ".edit-music-page audio" );
		var saveMusicBtn = querySelector( ".edit-music-make-sure" );
		querySelector( ".close-edit-music-page-hide-btn" ).onclick = function () {
			page.classList.add( "hide" );
		};
		page.addEventListener( "mouseover", function () {
			page.classList.add( "top" );
		}, false );
		page.addEventListener( "mouseout", function () {
			page.classList.remove( "top" );
		}, false );
		// 保存音乐设置
		saveMusicBtn.onclick = function () {
			if ( page.querySelector( ".select.item" ) ) {
				// 如果存在被选中的音乐
				saveMusicBtn.musicUrl = page.querySelector( ".select.item .name" ).music.url;
				// 首先组织数据
				fp.message( {
					text : "正在保存设置"
				} );
				saveUserConfig( true, function ( data ) {
					// todo 此处可以添加音乐保存是否成功的提示
					page.classList.add( "hide" );
					data.code == 200 && fp.message( {
						text : "保存成功"
					} );
				} );
			}
			else {
				fp.message( {
					text : "请选一首喜欢的音乐"
				} );
			}
		};
		openBtn.onclick = function () {
			page.classList.remove( "hide" );
		};
		var curSwitch = systemMusicBtn;
		curSwitch.classList.add( "select" );
		systemMusicBtn.onclick = function () {
			if ( curSwitch != systemMusicBtn ) {
				curSwitch.classList.remove( "select" );
				curSwitch = systemMusicBtn;
				curSwitch.classList.add( "select" );
				// 切出系统音乐列表
				systemList.classList.add( "select" );
				userList.classList.remove( "select" );
			}
		};
		userMusicBtn.isLoadData = false;
		userMusicBtn.onclick = function () {
			if ( curSwitch != userMusicBtn ) {
				curSwitch.classList.remove( "select" );
				curSwitch = userMusicBtn;
				curSwitch.classList.add( "select" );
				// 切出用戶音乐列表
				systemList.classList.remove( "select" );
				if ( !userMusicBtn.isLoadData ) {
					var container = userList.querySelector( ".music-list" );
					userList.classList.add( "select" );
					container.classList.add( "loading" );
					// 如果还没有加载过数据，先加载数据
					fpInvokeAPI.getMusicListByCategory( "custom", function ( data ) {
						container.classList.remove( "loading" );
						if ( data.code == 200 ) {
							userMusicBtn.isLoadData = true;
							loopArray( data.data, function ( music, i ) {
								var item = systemTemPlate.make( ".user-music-item" );
								var name = item.querySelector( ".name" );
								var btn = item.querySelector( ".btn" );
								item.musicName = music.Name + ".mp3";
								name.innerHTML = music.Name;
								name.music = {
									Id : music.Id,
									url : music.Url,
									MusicType : music.MusicType
								};
								onTap( name, function () {
									// 选中音乐
									// 先去掉已经选择的
									page.querySelector( ".item.select" ) && page.querySelector( ".item.select" ).classList.remove( "select" );
									name.parentNode.classList.add( "select" );
								} );
								onTap( btn, function () {
									if ( !btn.classList.contains( "play" ) ) {
										// 沒播放，則進行播放
										//　如果此时还有其他音乐在播放，修改对方的播放图标
										page.querySelector( ".play.btn" ) && page.querySelector( ".play.btn" ).classList.remove( "play" );
										btn.classList.add( "play" );
										audio.src = name.music.url;
										audio.play();
									}
									else {
										// 正在播放，則暫停
										btn.classList.remove( "play" );
										audio.pause();
									}
								} );
								container.appendChild( item );
							} );
						}
					} );
				}
			}
		};
		closeBtn.onclick = function () {
			page.classList.add( "hide" );
		};
		// 用户上传音乐按钮
		updateMusicBtn.onclick = function () {
			inputMusicFile.click();
		};
		inputMusicFile.onchange = function () {
			// 得到音乐名字等信息
			if ( inputMusicFile.files.length == 0 ) {
				return;
			}
			var musicName = inputMusicFile.files[0].name;
			var musicLastModified = inputMusicFile.files[0].lastModified;
			var musicSize = inputMusicFile.files[0].size;
			// 先判断文件是否超过大小限制
			if ( musicSize > 4 * MB ) {
				alert( "音乐文件不能超过4MB~" );
				return;
			}
			// 同一首音乐不允许上传两次，判断是不是同一首音乐先看名称，然后再看它的时间戳
			var userMusicItems = userList.querySelectorAll( ".user-music-item" );
			var isLive = false;
			if ( userMusicItems.length != 0 ) {
				for ( var i = 0; i < userMusicItems.length; i++ ) {
					if ( userMusicItems[i].musicName == musicName ) {
						alert( "同一首音乐只能上传一次哟~!" );
						isLive = true;
						break;
					}
				}
				if ( !isLive ) {
					// 如果上传的音乐不重复，则进行后续处理
					processUpload( inputMusicFile.files[0] );
				}
			}
			else {
				// 目前还没上传过音乐，直接略过是不是同一首音乐的检查
				processUpload( inputMusicFile.files[0] );
			}
			function processUpload( file ) {
				var fd = new FormData();
				fd.append( "blob-fileName", file.name );
				fd.append( "MyFile", file, file.name );// 在某些IDE中會该句代码可能会提示报错，忽略，因为目前支队chrome内核支持，所以忽略
				// 在列表中生成项
				var item = systemTemPlate.make( ".user-music-item" );
				item.classList.add( "loading" );
				item.musicName = file.name;
				var name = item.querySelector( ".name" );
				name.innerHTML = file.name.substring( 0, file.name.indexOf( "." ) );
				var list = querySelector( ".edit-music-user-music-list  .music-list" );
				list.insertBefore( item, list.querySelector( ".user-music-item" ) );
				var btn = item.querySelector( ".btn" );
				var syncxhr = null;
				var uploadxhr = null;
				onTap( btn, function () {
					if ( item.classList.contains( "loading" ) ) {
						// 如果还在加载状态，点击的时候abort上传的xhr
						syncxhr && syncxhr.abort();
						uploadxhr && uploadxhr.abort();
						list.removeChild( item );
					}
					else {
						// 已经上传完毕，点击播放音乐
						if ( !btn.classList.contains( "play" ) ) {
							// 沒播放，則進行播放
							//　如果此时还有其他音乐在播放，修改对方的播放图标
							page.querySelector( ".play.btn" ) && page.querySelector( ".play.btn" ).classList.remove( "play" );
							btn.classList.add( "play" );
							audio.src = name.music.url;
							audio.play();
						}
						else {
							// 正在播放，則暫停
							btn.classList.remove( "play" );
							audio.pause();
						}
					}
				} );
				uploadxhr = fpInvokeAPI.uploadUserMusic( {
					data : fd,
					success : function ( data ) {
						console.log( "okokok", data );
						item.url = data.data.Url;
						// 成功上传到第三方服务器后和我们的服务器同步
						syncxhr = fpInvokeAPI.syncUploadMusic( {
							FileName : data.data.FileName,
							Url : data.data.Url
						}, function ( syndata ) {
							if ( syndata.code == 200 ) {
								CSS( item.querySelector( ".already-progress" ), {
									width : "100%"
								} );
								setTimeout( function () {
									item.classList.remove( "loading" );
									// 上传完毕之后给这个条目注册事件：播放和选中
									name.music = {
										Id : data.data.ID,
										url : data.data.Url,
										MusicType : 2
									};
									onTap( name, function () {
										var cur = page.querySelector( ".item.select" );
										cur && cur.classList.remove( "select" );
										item.classList.add( "select" );
									} );
								}, 1000 );
							}
						} );
					},
					progress : function ( e ) {
						//e.loaded / e.total
						CSS( item.querySelector( ".already-progress" ), {
							width : e.loaded / e.total * 100 * 0.8 + "%"
							// 由于上传的进度实际上是分为两部分，一部分是上传到第三方服务器，另外一部分是和我方服务器做同步
							// 向第三方服务器上传音乐传输的数据比较大，所以设置为总进度的80%（0.8）
						} );
					}
				} );
			}
		}
	}

	// 作品设置
	function editSetting() {
		var page = querySelector( ".edit-setting-page" );
		var changeThBtn = querySelector( ".virtual-input-file-btn" );
		var fileInput = querySelector( ".edit-setting-page .cropit-image-input" );
		var title = querySelector( ".edit-setting-page .edit-setting-title textarea" );
		var description = querySelector( ".edit-setting-page .edit-description textarea" );
		var descriptionCount = querySelector( ".edit-setting-page .edit-description .count" );
		var titleCount = querySelector( ".edit-setting-page .edit-setting-title .count" );
		var moreBtn = querySelector( ".edit-setting-page .more" );
		var moreBorder = querySelector( ".edit-setting-more-option-border" );
		var publicitySwitch = querySelector( ".edit-setting-switch-publicity" );// 公开开关
		var recommendSwitch = querySelector( ".edit-setting-switch-recommend" );// 推荐开关
		var closePageBtn = querySelector( ".close-edit-setting-page" );
		var openPageBtn = querySelector( ".edit-page-theme-setting-btn" );
		var makeSureBtn = querySelector( ".edit-setting-make-sure" );
		$( ".edit-setting-page .crop-img-border" ).cropit();
		page.addEventListener( "mouseover", function () {
			page.classList.add( "top" );
		}, false );
		page.addEventListener( "mouseout", function () {
			page.classList.remove( "top" );
		}, false );
		querySelector( ".close-edit-setting-page-hide-btn" ).onclick = function () {
			page.classList.add( "hide" );
		};
		changeThBtn.onclick = function () {
			fileInput.click();
		};
		// 监听标题的字数
		title.addEventListener( "keydown", function ( e ) {
			titleCount.innerHTML = this.value.length == 1 && e.keyCode == 8 ? 2 : this.value.length + "/" + this.maxLength;// 每次弹出这个页面都应该执行一次这行代码
		}, false );
		// 监听描述的字数
		description.addEventListener( "keydown", function ( e ) {
			descriptionCount.innerHTML = this.value.length == 1 && e.keyCode == 8 ? 2 : this.value.length + "/" + this.maxLength;// 每次弹出这个页面都应该执行一次这行代码
		}, false );
		moreBtn.onclick = function () {
			querySelector( ".edit-setting-page .triangle" ).classList.toggle( "show-more" );
			moreBorder.classList.toggle( "show-more" );
		};
		publicitySwitch.onclick = function () {
			this.classList.toggle( "close" );
		};
		recommendSwitch.onclick = function () {
			this.classList.toggle( "close" );
		};
		closePageBtn.onclick = function () {
			page.classList.add( "hide" );
		};
		openPageBtn.onclick = function () {
			page.classList.remove( "hide" );
		};
		makeSureBtn.onclick = function () {
			fp.message( {
				text : "正在保存您的配置"
			} );
			saveUserConfig( false, function ( data ) {
				if ( data.code == 200 ) {
					fp.message( {
						text : "保存成功"
					} );
					// 更新作品标志
					querySelector( ".edit-page-theme-thumbnail img" ).src = data.data;
					//　更新作品标题
					querySelector( ".edit-page-theme-title" ).innerHTML = querySelector( ".edit-setting-title textarea" ).value;
				}
				page.classList.add( "hide" );
			} );
		}
	}

	// 预览页面
	function presetPreviewPage() {
		var backBtn = previewPage.querySelector( ".preview-page-back-btn" );
		var iframe = previewPage.querySelector( "iframe" );
		iframe.onload = function () {
			try {
				iframe.contentDocument.querySelector( ".preview-page" ).parentNode.removeChild( iframe.contentDocument.querySelector( ".preview-page" ) );
			}
			catch ( e ) {
			}
		};
		backBtn.onclick = function () {
			previewPage.classList.remove( "show" );
			iframe.src = "";
		};
		querySelector( ".edit-page-preview.edit-page-icon" ).onclick = function () {
			previewPage.classList.add( "show" );
			iframe.src = virtualPath + "/" + workId;
		};
		// 上一页
		querySelector( ".preview-page-pre-page" ).onclick = function () {
			iframe.contentWindow.jumpPage( iframe.contentWindow.curPageIndex - 1 );
		};
		//　下一页
		querySelector( ".preview-page-next-page" ).onclick = function () {
			iframe.contentWindow.jumpPage( iframe.contentWindow.curPageIndex + 1 );
		};
	}

	presetPreviewPage();
	editSetting();
	pageEditMusic();
	slidePageEditWord();
	slidePageEditBgImg();
	presetAddPage();

	function loadTemplate() {
		var wall = querySelector( ".edit-add-page-template-wall" );
		var makeSure = querySelector( ".edit-page-add-page-setting-page .edit-add-page-btn" );
		// 如果没有加载过数据，则在页面打开时候获取数据
		addPageSettingPage.classList.add( "loading" );
		fpInvokeAPI.getAllTemplate( function ( data ) {
			// 制作模板
			console.log( data );
			addPageSettingPage.isLoadTemplate = true;
			addPageSettingPage.classList.remove( "loading" );
			loopArray( data.data, function ( template, i ) {
				// state为0，以及在不支持名单中的版式不会显示，也就是没法添加这些版式页面
				if ( template.State == 1 && !notSurppotList[template.ID] ) {
					var ne = systemTemPlate.make( ".template-item-border" );
					CSS( ne.querySelector( ".template-thumbnail" ), {
						"background" : "url(" + template.Thumbnail + ")",
						"background-size" : "cover"
					} );
					var thumbnail = ne.querySelector( ".template-thumbnail" );
					ne.querySelector( ".template-description" ).innerHTML = template.Description;
					wall.appendChild( ne );
					if ( i == 0 ) {
						thumbnail.classList.add( "select" );
						thumbnail.classList.add( "" + i );
						wall.curselect = thumbnail;
						makeSure.templateID = template.ID;
					}
					onTap( thumbnail, function () {
						wall.curselect.classList.remove( "select" );
						thumbnail.classList.add( "select" );
						wall.curselect = thumbnail;
						makeSure.templateID = template.ID;
						// 保存的时候获取当前页面的id不用去其他地方取了，直接在确认按钮上找templateID
					} );
				}
			} );
		} );
	}

	onTap( addPageBtn, function () {
		openInnerPage( addPageSettingPage );
		if ( addPageSettingPage.isLoadTemplate == false ) {
			loadTemplate();
		}
	} );

	function makePage( data, callback ) {
		function getPosition( p ) {
			switch ( p ) {
				case "上":
					return "top";
				case "中":
					return "middle";
				case "下":
					return "bottom";
			}
			return "middle";
		}

		function hexToRgb( hex ) {
			var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec( hex );
			return result ? {
				r : parseInt( result[1], 16 ),
				g : parseInt( result[2], 16 ),
				b : parseInt( result[3], 16 )
			} : null;
		}

		var modeName,
			imgArr = [],
			textArr = [],
			videoArr = [],
			imageinfo = [],
			location = [],
			actionlinks = [],
			position = [],
			signup = {};
		var imgMediaInfo = [];
		var textMediaInfo = [];
		loopArray( data.Medias, function ( media ) {
			var attr = JSON.parse( media.Attributes );
			switch ( media.Category ) {
				// 纯文字
				case 1: //单行文本
				case 56: //多行文字
					media.Text && textArr.push( media.Text );
					media.Text && textMediaInfo.push( media );
					break;
				// 图片、有可能是纯图片、文字转图片、报名、遮罩
				case 2:// 图片
				case 7:// 文字转图片
				case 9:// 报名
				case 11:// 高级报名
				case 57:// 遮罩
				case 58:// 文字转图片拼接
					if ( media.Category == 57 ) {
						if ( data.Layout == "custom" ) {
							// 不是自定义的版式，mask不会加入到imgMediaInfo中
							imgMediaInfo.push( media );
							if ( media.Uri ) {
								imgArr.push( media.Uri );
							}
							else {
								if ( attr.Alpha ) {
									var rgb = hexToRgb( attr.Color );
									imgArr.push( "rgba(" + rgb.r + "," + rgb.g + "," + rgb.b + "," + attr.Alpha + ")" );
								}
								else {
									imgArr.push( attr.Color );
								}
							}
						}
					}
					else {
						if ( media.Uri ) {
							media.Uri && imgArr.push( media.Uri );
						}
						else {
							imgArr.push( "https://cloud7static.blob.core.chinacloudapi.cn/chuye/content/image/texteditspace.png" );
						}
						imgMediaInfo.push( media );
					}

					if ( data.Layout == "custom" ) {
						attr && imageinfo.push( {
							x : attr.X,
							y : attr.Y,
							animation : attr.Animation,
							width : attr.W,
							height : attr.H,
							rotate : attr.R,
							maskRadius : attr.BorderRadius,
							"animation-delay" : attr.AnimationDelay,
							"animation-duration" : attr.AnimationDuration
						} );
					}
					if ( media.Category == 11 ) {
						media.Text && position.push( getPosition( media.Text ) );
						//todo: 高级报名
						signup.formId = "";
						signup.template = "{}";
					}
					break;
				case 5:
					media.ActionLink && videoArr.push( media.ActionLink );
					break;
				case 3:
					if ( media.Text ) {
						var loc = media.Text.split( '$' );
						location.push( {
							lng : loc[0],
							lat : loc[1],
							name : loc[2],
							address : loc[3]
						} );
					}
					break;
				case 6:
					media.Text && position.push( getPosition( media.Text ) );
					media.ActionLink && actionlinks.push( media.ActionLink );
					break;
			}
		} );
		modeName = data.Layout;
		var page = ppt.layoutPage( {
			label : modeName,
			image : imgArr,
			text : textArr,
			video : videoArr,
			imageinfo : imageinfo,
			location : location,
			position : position
		}, callback );
		page.pageInfo = {
			imageInfo : imageinfo,
			textInfo : textArr,
			imgMediaInfo : imgMediaInfo,
			textMediaInfo : textMediaInfo,
			pageData : data
		};
		if ( notSurppotList[data.LayoutId] ) {
			// 如果是不支持的版式，添加水印
			var notSurppotImage = new Image();
			notSurppotImage.classList.add( "not-surppot-image" );
			notSurppotImage.src = staticImgSrc( "image/not-surppot.png" );
			page.appendChild( notSurppotImage );
		}
		return page;
	}

	// 将一个页面数据变成一个页面dom，添加到右侧list，注册事件
	function appendOnePage( pageData, i, renderFinishedCallBack ) {
		var pageListBorder = querySelector( ".edit-page-left ul" );
		var li = systemTemPlate.make( ".page-list" );
		var page = makePage( pageData, function () {
			page.pageInfo.pageData = pageData;
			renderFinishedCallBack && renderFinishedCallBack( page );
			onTap( li, function () {
				// 将影像映射到手机屏幕上,注意这里不要直接用page，因为这里ontap可以在任何时候点击，
				// 页面有可能修改过，所以为了保证实时性，必须是query出来的map到主屏幕
				pageListBorder.querySelector( "li.select" ).classList.remove( "select" );
				li.classList.add( "select" );
				mappingToScreen( li.querySelector( ".page" ) );
				closeAllSlidePage();
			} );
		} );
		li.appendChild( page );
		li.classList.add( "show" );
		var deleteBtn = li.querySelector( ".delete-btn" );
		li.Guid = pageData.Guid;
		deleteBtn.Guid = pageData.Guid;
		deleteBtn.Id = pageData.Id;
		li.pageData = pageData;// 因为cloneNode不会复制用户自定义的dom属性，所以需要以li为载体，向映射到屏幕上的dom传输数据
		onTap( deleteBtn, function () {
			if ( confirm( "确认要删除该页面么？" ) ) {
				fpInvokeAPI.deletePage( deleteBtn.Guid, function ( data ) {
					// todo 可以在这里做删除是否成功的验证
					console.log( data )
				} );
				//　直接從列表中移除
				li.classList.add( "hide" );
				li.classList.remove( "show" );
				// 重新编号
				loopArray( pageListBorder.querySelectorAll( "li.show" ), function ( li, i ) {
					li.querySelector( ".thumbnail-page-list-item-num span" ).innerHTML = i + 1;
				} );
				if ( pageListBorder.querySelectorAll( "li" ).length == pageListBorder.querySelectorAll( "li.hide" ).length ) {
					// 如果都删完了，清空手机屏幕，弹出新建页面配置页
					screen.innerHTML = "";
					openInnerPage( addPageSettingPage );
					if ( addPageSettingPage.isLoadTemplate == false ) {
						loadTemplate();
					}
				}
				else {
					//优先选下一个，也就是说第4个被删除，则默认显示第5个（由于被删除的页面并没有从dom中移除）
					var next = pageViewJumpTo( 1, true );
					if ( next.el == null ) {
						next = pageViewJumpTo( -1, true );
					}
					mappingToScreen( next.el.querySelector( ".page" ) );
				}
			}
		} );
		li.querySelector( "span" ).innerHTML = i;
		pageListBorder.appendChild( li );
		return li;
	}

	// 将左侧列表中的页面映射到手机屏幕上
	function mappingToScreen( page ) {
		if ( querySelector( "li.page-list.select" ).pageData.Id != page.pageInfo.pageData.Id ) {
			/* 如果此時被選中的与要渲染的页面不一致，则直接return
			 造成不一致的原因主要是因为页面被渲染（makePage）是异步的，必须等到页面被渲染出来才能映射到屏幕上
			 而用户可能等不及映射完毕就去选看其它页面了，这时候就会出现不一致的情况
			 */
			return;
		}
		var editWordPage = querySelector( ".slide-page-edit-word" );
		var editImagePage = querySelector( ".slide-page-edit-bgimg" );
		// 得到一个元素相对于页面的坐标，有些元素是嵌套包含的
		function getPageCo( el ) {
			var x = 0;
			var y = 0;
			while ( true ) {
				if ( el.classList.contains( "page" ) ) {
					break;
				}
				// 在这里其实是忽略了一些东西，比如说border的宽度没有计算在内,目前没有见到设置border的元素
				//　如果将来有了，用这个方法获取：getComputedStyle( el, null )["border-width"]
				x += el.x;
				y += el.y;
				el = el.parentNode;
			}
			return {
				x : x,
				y : y
			}
		}

		// 初始化文字编辑页面
		function initSlideWordPage( info, media ) {
			editWordPage.textInfo = media;
			editWordPage.selectColor( info.Color );
			editWordPage.selectFontAnimation( info.Animation );
			editWordPage.selectFontFamily( info.FontFamily );
			editWordPage.fillText( media.Text );
		}

		var screen = querySelector( ".edit-page-phone-screen" );
		var bigPage = page.cloneNode( true );
		bigPage.pageInfo = page.pageInfo;
		var newPlugs = bigPage.querySelectorAll( ".layout-component-from-data" );
		// 添加透明遮罩层，注册事件
		var virtualLayer = element( "div", {classList : "virtual-layer"}, null );
		if ( !notSurppotList[page.pageInfo.pageData.LayoutId] ) {
			// 只对支持的版式进行处理
			// 生成可编辑对象
			loopArray( page.querySelectorAll( ".layout-component-from-data" ), function ( plug, i ) {
				newPlugs[i].dataSource = plug.dataSource;
				var editableObj = element( "div", {classList : "virtual-layer-editable-obj"}, virtualLayer );
				var info = null;
				if ( plug.dataSource.from == "image" ) {
					info = JSON.parse( page.pageInfo.imgMediaInfo[plug.dataSource.index].Attributes );
					if ( page.pageInfo.imgMediaInfo[plug.dataSource.index].Category == 57 ) {
						return;
					}
					else if ( page.pageInfo.imgMediaInfo[plug.dataSource.index].Category == 7 ) {
						// 如果是文字传图片的话，应该按照文字来处理
						onTap( editableObj, function () {
							// 点击选择之后要有被选中的的效果
							virtualLayer.querySelector( ".virtual-layer-editable-obj.select" ) && virtualLayer.querySelector( ".virtual-layer-editable-obj.select" ).classList.remove( "select" );
							editableObj.classList.add( "select" );
							// 打开编辑文字页面
							editWordPage.pageData = page.pageInfo.pageData;
							initSlideWordPage( info, page.pageInfo.imgMediaInfo[plug.dataSource.index] );
							querySelector( ".slide-page-edit-word" ).classList.remove( "pure-word" );
							openSlidePage( querySelector( ".slide-page-edit-word" ) );
						} );
					}
					else {
						onTap( editableObj, function () {
							// 点击选择之后要有被选中的的效果
							virtualLayer.querySelector( ".virtual-layer-editable-obj.select" ) && virtualLayer.querySelector( ".virtual-layer-editable-obj.select" ).classList.remove( "select" );
							editableObj.classList.add( "select" );
							// 打开编辑图片页面
							editImagePage.pageData = page.pageInfo.pageData;
							editImagePage.mediaData = page.pageInfo.imgMediaInfo[plug.dataSource.index];
							// 图片有大有小，需要调整页面编辑框的大小
							// 图片的大小可以直接参照传输来的数据
							CSS( editImagePage.querySelector( ".cropit-image-preview" ), {
								height : 256 * info.H / info.W + "px",
								"margin-top" : -128 * info.H / info.W + "px"
							} );
							$( ".slide-page-edit-bgimg .crop-img-border" ).cropit( 'destroy' );
							$( ".slide-page-edit-bgimg .crop-img-border" ).cropit( {imageState : {src : page.pageInfo.imgMediaInfo[plug.dataSource.index].Uri}} );
							querySelector( ".slide-page-edit-bgimg input.cropit-image-zoom-input.edit-bgimg-range" ).disabled = "disabled";
							openSlidePage( querySelector( ".slide-page-edit-bgimg" ) );
						} );
					}
				}
				else if ( plug.dataSource.from == "text" ) {
					info = JSON.parse( page.pageInfo.textMediaInfo[plug.dataSource.index].Attributes );
					onTap( editableObj, function () {
						// 点击选择之后要有被选中的的效果
						virtualLayer.querySelector( ".virtual-layer-editable-obj.select" ) && virtualLayer.querySelector( ".virtual-layer-editable-obj.select" ).classList.remove( "select" );
						editableObj.classList.add( "select" );
						//　打开编辑文字页面
						editWordPage.pageData = page.pageInfo.pageData;
						initSlideWordPage( info, page.pageInfo.textMediaInfo[plug.dataSource.index] );
						querySelector( ".slide-page-edit-word" ).classList.add( "pure-word" );
						openSlidePage( querySelector( ".slide-page-edit-word" ) );
					} );
				}
				if ( info.W == 320 && info.H == 504 ) {
					// 是背景圖
					info && CSS( editableObj, {
						width : info.W - 2 + "px",
						height : info.H - 2 + "px",
						left : info.X + "px",
						top : info.Y + "px",
						"-webkit-transform" : "scale(" + plug.scale + ") rotateZ(" + (plug.rotate * 360 / (2 * Math.PI)) + "deg)",
						"z-index" : 1
					} );
				}
				else {
					info && CSS( editableObj, {
						width : (plug.offsetWidth || info.W) - 2 + "px",
						height : (plug.offsetHeight || info.H) - 2 + "px",
						left : getPageCo( plug ).x + "px",
						top : getPageCo( plug ).y - 1 + "px",
						"-webkit-transform" : "scale(" + plug.scale + ") rotateZ(" + (plug.rotate * 360 / (2 * Math.PI)) + "deg)",
						"z-index" : 2
					} );
				}
			} );
		}
		screen.innerHTML = "";
		screen.appendChild( virtualLayer );
		screen.appendChild( bigPage );
	}

	// 得到用户配置的数据，用于初始化
	function initPageView() {
		fpInvokeAPI.getPageData( function ( data ) {
			// 取到数据之后去掉loading类，加载标志就会消失
			editPageLeft.classList.remove( "loading" );
			if ( data.code != 200 ) {
				alert( "网络或服务器有问题，请稍后再试" );
				return;
			}
			// 根据得到的该作品的基本信息初始化一些配置内容
			if ( data.data ) {
				// 设置页面的标题
				data.data.Title && (querySelector( ".edit-setting-title textarea" ).value = data.data.Title);
				data.data.Description && (querySelector( ".edit-description textarea" ).value = data.data.Description);
				data.data.Thumbnail && (querySelector( ".edit-setting-page .default-thumbnail" ).src = data.data.Thumbnail);
				// 翻页动画
				data.data.Switch && (querySelector( ".edit-setting-page .page-turning-animation" ).value = data.data.Switch);
				// 翻页手势
				data.data.Mode && (querySelector( ".edit-setting-page .page-turning-gesture" ).value = data.data.Mode);
				// 主页面手机上的标题
				data.data.Title && (querySelector( ".edit-page-phone-content-border .edit-page-theme-title" ).innerHTML = data.data.Title);
				querySelector( ".edit-music-make-sure" ).musicUrl = data.data.BackgroundMusic;
				querySelector( ".edit-page-theme-thumbnail img" ).src = data.data.Thumbnail;
				querySelector( ".preview-page-share-thumbnail" ).src = data.data.Thumbnail;
				querySelector( ".preview-page-descrption" ).innerHTML = data.data.Description;
				querySelector( ".preview-page-share-title" ).innerHTML = data.data.Title;

				var switcher = querySelector( ".edit-setting-page .page-turning-animation" );
				if ( data.data.Mode && data.data.Mode == "push" ) {
					switcher.disabled = true;
					switcher.style.color = "#cfcfcf";
				}
				else {
					switcher.disabled = false;
					switcher.style.color = "#626262";
				}
			}
			// 进行页面渲染
			if ( data.data.PageItems.length == 0 ) {
				querySelector( ".edit-page-phone-content-border" ).classList.remove( "loading" );
				// todo 如果现在还没有页面，则自动弹出添加页面菜单
				openInnerPage( addPageSettingPage );
				if ( addPageSettingPage.isLoadTemplate == false ) {
					loadTemplate();
				}
			}
			else {
				var screen = querySelector( ".edit-page-phone-screen" );
				loopArray( data.data.PageItems, function ( pagedata, i ) {
					var li = appendOnePage( pagedata, i + 1 );
					if ( i == 0 ) {
						// 将第一页的影像映射到手机屏幕上
						li.classList.add( "select" );
						var page = makePage( pagedata, function () {
							querySelector( ".edit-page-phone-content-border" ).classList.remove( "loading" );
							page.pageInfo.pageData = pagedata;
							mappingToScreen( page );
						} );
						screen.appendChild( page );
					}
				} );
			}

			window.customCopyright = data.data.CustomCopyright;
			querySelector( ".edit-setting-page .page-turning-gesture" ).onchange = function () {
				var val = this.value, switcher = querySelector( ".edit-setting-page .page-turning-animation" );
				if ( val == "push" ) {
					switcher.disabled = true;
					switcher.style.color = "#cfcfcf";
				}
				else {
					switcher.disabled = false;
					switcher.style.color = "#626262";
				}
			};
		} );
	}

	// 上一頁、下一页使用，删除一个页面后也会调用
	function pageViewJumpTo( step, isNotMove ) {
		var pageListBorder = querySelector( ".edit-page-left ul" );
		// 选出当前选中的
		var cur = pageListBorder.querySelector( "li.select" );
		if ( !cur ) {
			return;
		}
		var ds = 0;// 记录下翻的距离（由于删除页面时候并没有真正移除dom，只是用display加以控制，所以需要记录这个ds控制下翻的距离）
		var next = null;
		if ( step == 1 ) {
			//往后翻
			while ( cur.nextElementSibling ) {
				if ( !cur.nextElementSibling.classList.contains( "hide" ) ) {
					// 如果存在并且没有被删除就是我们要找的
					next = cur.nextElementSibling;
					break;
				}
				ds++;
				cur = cur.nextElementSibling;
			}
		}
		else {
			// 向前翻
			while ( cur.previousElementSibling ) {
				if ( !cur.previousElementSibling.classList.contains( "hide" ) ) {
					// 如果存在并且没有被删除就是我们要找的
					next = cur.previousElementSibling;
					break;
				}
				ds++;
				cur = cur.previousElementSibling;
			}
		}
		if ( next != null ) {
			// 如果被找到了,则更改
			pageListBorder.querySelector( "li.select" ).classList.remove( "select" );
			next.classList.add( "select" );
			if ( isNotMove != true && document.querySelectorAll( ".edit-page-left ul li.show" ).length * 154 > pageListBorder.offsetHeight ) {
				// 调整ul的scrolltop使被选中的li始终在视野之内
				// 计算可以完整展示几个li
				var count = Math.floor( pageListBorder.offsetHeight / 154 );
				var curindex = parseInt( next.querySelector( ".thumbnail-page-list-item-num span" ).innerHTML );
				if ( (curindex - 1) * 154 > pageListBorder.scrollTop + pageListBorder.offsetHeight || (curindex - 1) * 154 < pageListBorder.scrollTop ) {
					// 不在可见范围内
					if ( step == 1 ) {
						pageListBorder.scrollTop = (curindex - 1) * 154;
					}
					else {
						if ( curindex <= count ) {
							pageListBorder.scrollTop = 0;
						}
						else {
							pageListBorder.scrollTop = curindex * 154 - pageListBorder.offsetHeight;
						}
					}
				}
			}
			return {
				el : next,
				ds : ds
			};
		}
		else {
			return {
				el : null,
				ds : null
			};
		}
	}

	// 上一页与下一页按钮
	onTap( querySelector( ".edit-page-pre-page-btn" ), function () {
		// 上一页
		var li = pageViewJumpTo( -1 );
		if ( li.el != null ) {
			mappingToScreen( li.el.querySelector( ".page" ) );
		}
		closeAllSlidePage();
	} );
	onTap( querySelector( ".edit-page-next-page-btn" ), function () {
		// 上一页
		var li = pageViewJumpTo( 1 );
		if ( li.el != null ) {
			mappingToScreen( li.el.querySelector( ".page" ) );
		}
		closeAllSlidePage();
	} );

	// 获取音乐数据，为做展示用
	function preLoadingMusic() {
		// 音乐分类框
		var page = querySelector( ".edit-music-page" );
		var musicListCach = [];
		var musicListBorder = querySelector( ".edit-music-system-music-list .music-list" );
		var audio = querySelector( ".edit-music-page audio" );
		var systemMusicList = querySelector( ".edit-music-system-music-list" );
		var cats = [];// 因为目前的接口把自定义也算作在内，所以需要过滤一遍，以防止将来顺序发生变化导致出现错误
		var musicCategoryBorder = querySelector( ".edit-music-page .edit-music-system-class" );
		audio.addEventListener( "ended", function () {
			page.querySelector( ".play.btn" ) && page.querySelector( ".play.btn" ).classList.remove( "play" );
		}, false );
		audio.addEventListener( "error", function ( e ) {
			alert( "对不起，该音乐暂时无法播放" );
			page.querySelector( ".play.btn" ) && page.querySelector( ".play.btn" ).classList.remove( "play" );
		}, false );
		fpInvokeAPI.getMusicCategory( function ( data ) {
			musicCategoryBorder.classList.remove( "loading" );
			if ( data.code == 200 ) {
				loopArray( data.data, function ( cat ) {
					cat != "自定义" && cats.push( cat );
				} );
				loopArray( cats, function ( Category, i ) {
					var catBtn = element( "div", {"classList" : "btn"}, musicCategoryBorder );
					catBtn.innerHTML = Category;
					catBtn.isGetList = false;
					// 点击种类按钮的时候再去获取列表
					catBtn.onclick = function () {
						musicCategoryBorder.querySelector( "div.select" ) && musicCategoryBorder.querySelector( "div.select" ).classList.remove( "select" );
						catBtn.classList.add( "select" );
						var curlistpage = systemMusicList.querySelector( ".music-list .inner-music-list.show" );
						if ( curlistpage ) {
							// 关闭当前列表
							curlistpage.classList.remove( "show" );
							curlistpage.classList.add( "hide" );
						}
						// 没有发送过数据则发送
						if ( !musicListCach[i] ) {
							var musicList = element( "div", {
								"classList" : ["inner-music-list", "loading", "show", "cat-" + i]
							}, systemMusicList );
							element( "div", {
								"classList" : ["loading-icon", "edit-page-icon"]
							}, musicList );
							musicListCach[i] = musicList;// 做缓存
							musicListBorder.appendChild( musicListCach[i] );
							// 发送获取指定分类音乐列表的请求
							fpInvokeAPI.getMusicListByCategory( Category, function ( data ) {
								if ( data.code == 200 ) {
									catBtn.isGetList = true;
									var list = musicListBorder.querySelector( ".inner-music-list.cat-" + i );
									list.classList.remove( "loading" );
									musicListCach[i].classList.remove( "loading" );
									loopArray( data.data, function ( music, i ) {
										var item = systemTemPlate.make( ".system-music-item" );
										var name = item.querySelector( ".name" );
										var playbtn = item.querySelector( ".btn" );
										name.innerHTML = music.Name;
										name.music = {
											Id : music.Id,
											url : music.Url,
											MusicType : music.MusicType
										};
										onTap( name, function () {
											// 选中音乐
											// 先去掉已经选择的
											page.querySelector( ".item.select" ) && page.querySelector( ".item.select" ).classList.remove( "select" );
											name.parentNode.classList.add( "select" );
										} );
										onTap( playbtn, function () {
											if ( !playbtn.classList.contains( "play" ) ) {
												// 沒播放，則進行播放
												//　如果此时还有其他音乐在播放，修改对方的播放图标
												page.querySelector( ".play.btn" ) && page.querySelector( ".play.btn" ).classList.remove( "play" );
												playbtn.classList.add( "play" );
												audio.src = name.music.url;
												audio.play();
											}
											else {
												// 正在播放，則暫停
												playbtn.classList.remove( "play" );
												audio.pause();
											}
										} );
										list.appendChild( item );
									} );
								}
							} );
						}
						else {
							systemMusicList.querySelector( ".music-list .inner-music-list.cat-" + i ).classList.remove( "hide" );
							systemMusicList.querySelector( ".music-list .inner-music-list.cat-" + i ).classList.add( "show" );
						}
					};
					i == 0 && catBtn.click();
				} );
			}
		} );
	}

	function initUserSetting() {
		fpInvokeAPI.getUserSetting( function ( data ) {
			if ( data.data ) {
				window.usersetting = data;
				var optionItem = $( "<option>" ).val( "custom" ).html( data.data.Author ).appendTo( $( ".edit-setting-page .page-turning-signature" ) );
				if ( window.customCopyright && window.customCopyright == true ) {
					optionItem.prop( "selected", "selected" );
				}
			}
		} );
	}

	function init() {
		ppt.initial( {
			width : 320,
			height : 504,
			contentSrc : function ( src ) {
				return window.contentPath + "/content/" + src.toLowerCase();
			}
		} );

		// 初始化頁面视图，请求数据、展示、注册事件
		initPageView();
		initUserSetting();
		// 加载音乐,给分类按钮注册事件等
		preLoadingMusic();
	}

	init();
})();
